package com.springboot.scheduled.demo.service.impl;

import com.springboot.scheduled.demo.constant.TaskConstant;
import com.springboot.scheduled.demo.service.DynamicTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ScheduledFuture;

/**
 * 动态定时任务 业务处理
 */
@Service
public class DynamicTaskServiceImpl implements DynamicTaskService {

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;


    @Override
    public String addAndStartTask(String id) {
        String cron = "0/5 * * * * *";
        if (TaskConstant.taskMap.containsKey(id)) {
            cron = "0/1 * * * * *";
        }
        String idt = "5693d85wskw5598skw";
        String finalCron = cron;
        ScheduledFuture future = taskScheduler.schedule(() -> {
            System.out.println("id = " + id + ",now -> " + LocalDateTime.now());
        }, t -> {
            System.out.println("是否有保存扎个值 = " + idt);
            CronTrigger cronTrigger = new CronTrigger(finalCron);
            return cronTrigger.nextExecutionTime(t);
        });
        System.out.println("查看是否同一个对象---" + future);
        TaskConstant.taskMap.put(id, future);

        return "add and start task success.";
    }

    @Override
    public String stopAndDelTask(String id) {

        ScheduledFuture future = TaskConstant.taskMap.get(id);
        if (future != null) {
            future.cancel(true);// 关闭任务
//            future = null; // 是否需要设置成null，达到释放资源的目的
            TaskConstant.taskMap.remove(id);// 从任务集合中移除
        }

        return "stop and delete task success.";
    }
}
